package com.lisa.auto.service.excel.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.lisa.auto.entity.excel.GoodsTmplPo;
import com.lisa.auto.entity.excel.OrderTmplPo;
import com.lisa.auto.entity.seveneleven.po.*;
import com.lisa.auto.service.excel.SevenElevenImportService;
import com.lisa.auto.tools.seveneleven.DataBaseConnect;
import com.lisa.auto.tools.seveneleven.SevenElevenComs;
import com.lisa.auto.tools.seveneleven.SevenElevenExcelConvertTool;
import com.lisa.auto.util.DateUtil;
import com.lisa.auto.util.ExcelUtils;
import com.lisa.auto.util.RegexUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author huangzhigang 2019/12/2
 */
@Service
public class SevenElevenImportServiceImpl implements SevenElevenImportService {

    static final Logger logger = LoggerFactory.getLogger(SevenElevenImportServiceImpl.class);

    @Override
    public void transVehicleExcel(MultipartFile orderFile, MultipartFile vehicleFile, HttpServletResponse response) {
        try {
            SevenElevenExcelConvertTool.readExcel(orderFile, vehicleFile, response);
        }catch (Exception e){
            logger.info(e.getMessage(), e);
        }
    }

	@Override
    public void importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            String param0 = "{\"笼车数量\":\"cageNum\",\"笼外胶箱\":\"glueBoxNum\",\"店铺\":\"shopId\"}";
            List<SevenElevenOrderPo> orderList = ExcelUtils.readExcel(file.getInputStream(), SevenElevenOrderPo.class, param0, null);
            String param1 = "{\"送货时间\":\"estimatedTime\",\"电话号码\":\"tel\",\"店铺\":\"shopId\"}";
            List<SevenElevenShopPo> shopList = ExcelUtils.readExcel(file.getInputStream(), SevenElevenShopPo.class, param1, null);
            Map<String, List<SevenElevenShopPo>> shopGroups = shopList.stream().collect(Collectors.groupingBy(SevenElevenShopPo::getShopId));
            List<SevenElevenShopAddrPo> shopAddrList = DataBaseConnect.execute(6);
            Map<String, List<SevenElevenShopAddrPo>> shopAddrGroups = shopAddrList.stream().collect(Collectors.groupingBy(SevenElevenShopAddrPo::getShopId));
            List<OrderTmplPo> result = new ArrayList<>();
            for (int i = 0; i < orderList.size(); i++) {
                SevenElevenOrderPo elevenShop = orderList.get(i);
                String shopId = elevenShop.getShopId();
                String cageNum = elevenShop.getCageNum();
                String glueBoxNum = elevenShop.getGlueBoxNum();
                if (StringUtils.isBlank(shopId) || StringUtils.isBlank(cageNum) || StringUtils.isBlank(glueBoxNum)){
                    continue;
                }
                if (!RegexUtils.checkNumber(shopId) || !RegexUtils.checkNumber(cageNum) || !RegexUtils.checkNumber(glueBoxNum)){
                    continue;
                }
                List<SevenElevenShopAddrPo> shopAddrPos = shopAddrGroups.get(shopId);
                if (CollectionUtils.isEmpty(shopAddrPos)){
                    continue;
                }
                List<SevenElevenShopPo> shopPoList = shopGroups.get(shopId);
                if (CollectionUtils.isEmpty(shopPoList)){
                    continue;
                }
                /** 外部订单号生成 */
                long idx = (System.currentTimeMillis() + (long)(Math.random() * 1000000));
                Map<String, List<OrderTmplPo>> orderGroup = result.stream().collect(Collectors.groupingBy(OrderTmplPo::getExtOrderNum));
                if (orderGroup.containsKey(idx)){
                    idx = (System.currentTimeMillis() + (long)(Math.random() * 1000000));
                }
                OrderTmplPo orderTmpl = SevenElevenComs.getInitData(idx);
                orderTmpl.setConsignee(shopId);
                SevenElevenShopPo shopPo = shopPoList.get(0);
                String estimatedTime = shopPo.getEstimatedTime();
                if (!StringUtils.isBlank(estimatedTime) && estimatedTime.contains("-")){
                    String[] timeArray = estimatedTime.split("-");
                    if (StringUtils.isBlank(timeArray[0])){
                        return;
                    }
                    String dateTime = DateUtil.format(DateUtil.DATE_1) + SevenElevenComs.EMPTY_ + timeArray[0] + ":00";
                    /** 取货开始时间 */
                    String startPickUp = DateUtil.format(DateUtil.addHour(DateUtil.parse(dateTime, DateUtil.DATE_TIME), -4L), DateUtil.DATE_TIME_2);
                    /** 取货结束时间 */
                    String endPickUp = DateUtil.format(DateUtil.addHour(DateUtil.parse(dateTime, DateUtil.DATE_TIME), -1L), DateUtil.DATE_TIME_2);
                    orderTmpl.setStartPickUp(startPickUp);
                    orderTmpl.setEndPickUp(endPickUp);

                    // 期望送达时间起
                    orderTmpl.setExtDeliveryStartTime(DateUtil.format(DateUtil.DATE) + SevenElevenComs.EMPTY_ + timeArray[0] + ":00");
                    /*期望送达时间止*/
                    orderTmpl.setExtDeliveryEndTime(SevenElevenComs.deliveryTime(timeArray[1]));
                }
                // 电话号码/联系电话
                String tel = shopPo.getTel();
                if (!StringUtils.isBlank(tel)){
                    orderTmpl.setConsigneeTelNum(tel);
                }
                SevenElevenShopAddrPo shopAddrPo = shopAddrPos.get(0);
                orderTmpl.setUnloadingAddr(shopAddrPo.getShopAddr());
                orderTmpl.setUnloadingAddrNo(shopAddrPo.getShopAddrNo());
                // 笼车数量
                int cageNumSum = StringUtils.isNotBlank(cageNum)?Integer.parseInt(cageNum):0;
                // 笼外胶箱
                int glueBoxNumSum = StringUtils.isNotBlank(glueBoxNum)?Integer.parseInt(glueBoxNum):0;
                if ((cageNumSum + glueBoxNumSum) == 0){
                    continue;
                }
                List<GoodsTmplPo> goodsTmplList = new ArrayList<>();
                List<GoodsTmplPo> goodsList = SevenElevenComs.goodsTmplDb(cageNumSum, SevenElevenComs.ONE_, goodsTmplList);
                List<GoodsTmplPo> goodsTmplPoList = SevenElevenComs.goodsTmplDb(glueBoxNumSum, SevenElevenComs.TWO_, goodsList);
                orderTmpl.setGoodsTmplList(goodsTmplPoList);
                result.add(orderTmpl);
            }
            String title = "城配基础数据"+DateUtil.format(DateUtil.DATE_TIME_1)+".xlsx";
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), OrderTmplPo.class, result);
            ExcelUtils.download(workbook, title, response);
        }catch (Exception e){
            logger.info(e.getMessage(), e);
        }
    }
}
